<template>
  <el-table-column
    :key="column.prop"
    :prop="column.prop"
    :label="column.label"
    :sort-method="(a, b) => mxSortMethod(a, b, column.prop, column.itemConfig?.sortMethodKey)"
    v-bind="{
      align: 'center',
      headerAlign: 'center',
      showOverflowTooltip: true,
      ...column.itemConfig,
    }"
  >
    <template v-if="column.componentHeader" #header>
      <slot
        v-if="column.headerSlot"
        name="headerColumn"
        :headerColumnConfig="column"
        :scope="{}"
      ></slot>
      <component
        v-else
        :is="componentFilter(column.componentHeader)"
        :prop="column.prop"
        :label="column.label"
        v-bind="column.headerConfig"
        @itemEvent="itemEvent('HeaderClick', { prop: column.prop, column })"
      >
        <template #headerTip>
          <slot
            name="headerColumn"
            :column="column"
            :scope="{}"
            :headerColumnConfig="column"
          ></slot>
        </template>
      </component>
    </template>
    <template v-if="column.children">
      <TableRecursion v-for="(item, index) of column.children || []" :key="index" :column="item" />
    </template>
    <template #default="scope" v-if="!column.children">
      <slot v-if="column.slot" name="column" :scope="scope" :column="column"></slot>
      <component
        v-else
        :is="componentFilter(column.component, scope.row, scope)"
        class="ignore"
        v-model="scope.row[column.prop]"
        :prop="column.prop"
        :scope="scope"
        :row="scope.row"
        size="small"
        parentType="table"
        v-bind="bindConfigFilter(column.bindConfig, scope.row, scope)"
        @itemEvent="data => emits('itemEvent', { ...data, scope: scope })"
      />
    </template>
  </el-table-column>
</template>

<script setup name="TableRecursion">
import { isFunction } from 'lodash';
import componentData from '../config';
import { numSortMethod, dateSortMethod, strSortMethod } from '@/utils/variables.js';

const props = defineProps({
  column: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emits = defineEmits(['itemEvent']);

function componentFilter(val = 'text', row, scope) {
  return isFunction(val) ? componentData[val({ row, scope })] : componentData[val] || val;
}

function bindConfigFilter(val, row, scope) {
  return isFunction(val) ? val({ row, scope }) : val;
}

/**
 * 排序方法  sortMethodKey控制排序类型
 * sortMethodKey=num,数字排序
 * sortMethodKey=date,日期排序
 * 不传，默认字符串排序
 */
function mxSortMethod(a, b, prop, sortMethodKey) {
  switch (sortMethodKey) {
    case 'num':
      return numSortMethod(a, b, prop);

    case 'date':
      return dateSortMethod(a, b, prop);

    default:
      return strSortMethod(a, b, prop);
  }
}
</script>
